package ynu.edu.controller;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import ynu.edu.common.Result;
import ynu.edu.entity.Food;
import ynu.edu.service.FoodService;

import java.util.List;

/**
 * 食品控制器
 */
@RestController
@RequestMapping(value = "/food", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
public class FoodController {
    
    private static final Logger logger = LoggerFactory.getLogger(FoodController.class);
    
    @Autowired
    private FoodService foodService;
    
    /**
     * 根据食品ID获取食品详情
     *
     * @param foodId 食品ID
     * @return 食品详情
     */
    @GetMapping("/{foodId}")
    @CircuitBreaker(name = "foodServiceBreaker", fallbackMethod = "getFoodByIdFallback")
    public Result<Food> getFoodById(@PathVariable("foodId") Integer foodId) {
        logger.info("根据ID获取食品，foodId: {}", foodId);
        Food food = foodService.getFoodById(foodId);
        logger.info("获取到食品: {}", food.getFoodName());
        return Result.success(food);
    }
    
    /**
     * 根据商家ID获取食品列表
     *
     * @param businessId 商家ID
     * @return 食品列表
     */
    @GetMapping("/business/{businessId}")
    @CircuitBreaker(name = "foodServiceBreaker", fallbackMethod = "getFoodsByBusinessIdFallback")
    public Result<List<Food>> getFoodsByBusinessId(@PathVariable("businessId") Integer businessId) {
        logger.info("根据商家ID获取食品列表，businessId: {}", businessId);
        List<Food> foods = foodService.getFoodsByBusinessId(businessId);
        logger.info("获取到食品数量: {}", foods.size());
        
        // 添加详细日志
        if (!foods.isEmpty()) {
            logger.info("第一个食品: id={}, name={}, price={}",
                foods.get(0).getFoodId(),
                foods.get(0).getFoodName(),
                foods.get(0).getFoodPrice());
        } else {
            logger.warn("未找到商家ID为{}的食品列表", businessId);
        }
        
        return Result.success(foods);
    }
    
    /**
     * 根据商家ID和食品ID获取食品详情
     *
     * @param businessId 商家ID
     * @param foodId     食品ID
     * @return 食品详情
     */
    @GetMapping("/business/{businessId}/food/{foodId}")
    @CircuitBreaker(name = "foodServiceBreaker", fallbackMethod = "getFoodByBusinessIdAndFoodIdFallback")
    public Result<Food> getFoodByBusinessIdAndFoodId(@PathVariable("businessId") Integer businessId, @PathVariable("foodId") Integer foodId) {
        logger.info("根据商家ID和食品ID获取食品，businessId: {}, foodId: {}", businessId, foodId);
        Food food = foodService.getFoodByBusinessIdAndFoodId(businessId, foodId);
        logger.info("获取到食品: {}", food.getFoodName());
        return Result.success(food);
    }
    
    /**
     * 根据商家ID和食品名称搜索食品
     *
     * @param businessId 商家ID
     * @param foodName   食品名称
     * @return 食品列表
     */
    @GetMapping("/search")
    @CircuitBreaker(name = "foodServiceBreaker", fallbackMethod = "searchFoodsByBusinessIdAndNameFallback")
    public Result<List<Food>> searchFoodsByBusinessIdAndName(@RequestParam Integer businessId, @RequestParam String foodName) {
        logger.info("搜索食品，businessId: {}, foodName: {}", businessId, foodName);
        List<Food> foods = foodService.searchFoodsByBusinessIdAndName(businessId, foodName);
        logger.info("搜索到食品数量: {}", foods.size());
        return Result.success(foods);
    }
    
    // 熔断降级方法
    public Result<Food> getFoodByIdFallback(Integer foodId, Exception e) {
        logger.error("获取食品详情失败，foodId: {}, 错误: {}", foodId, e.getMessage());
        return Result.failed("获取食品详情失败，请稍后再试: " + e.getMessage());
    }
    
    public Result<List<Food>> getFoodsByBusinessIdFallback(Integer businessId, Exception e) {
        logger.error("获取商家食品列表失败，businessId: {}, 错误: {}", businessId, e.getMessage());
        return Result.failed("获取商家食品列表失败，请稍后再试: " + e.getMessage());
    }
    
    public Result<Food> getFoodByBusinessIdAndFoodIdFallback(Integer businessId, Integer foodId, Exception e) {
        logger.error("获取食品详情失败，businessId: {}, foodId: {}, 错误: {}", businessId, foodId, e.getMessage());
        return Result.failed("获取食品详情失败，请稍后再试: " + e.getMessage());
    }
    
    public Result<List<Food>> searchFoodsByBusinessIdAndNameFallback(Integer businessId, String foodName, Exception e) {
        logger.error("搜索食品失败，businessId: {}, foodName: {}, 错误: {}", businessId, foodName, e.getMessage());
        return Result.failed("搜索食品失败，请稍后再试: " + e.getMessage());
    }
} 